#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
雷达仿真智能体系统 - 主程序入口
Radar Simulation Agent System - Main Entry Point

使用 PyQtAds 专业停靠窗口界面
Using PyQtAds Professional Docking System
"""

import sys
import os

# 添加项目路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

# 加载环境变量和配置
try:
    from dotenv import load_dotenv
    env_path = os.path.join(project_root, '.env')
    if os.path.exists(env_path):
        load_dotenv(env_path)
        print(f"SUCCESS: 已加载环境变量: {env_path}")

    # 导入并设置配置
    from radar_config import setup_environment
    setup_environment()
except ImportError:
    print("WARNING: 未安装python-dotenv，请运行: pip install python-dotenv")
except Exception as e:
    print(f"WARNING: 配置加载失败: {e}")


def safe_print(*args, **kwargs):
    """安全的打印函数，避免编码问题"""
    try:
        print(*args, **kwargs)
    except (UnicodeEncodeError, ValueError):
        # 如果编码出错，使用ASCII字符替换
        safe_args = []
        for arg in args:
            if isinstance(arg, str):
                safe_args.append(arg.encode('ascii', 'replace').decode('ascii'))
            else:
                safe_args.append(str(arg))
        print(*safe_args, **kwargs)
    except Exception:
        print("[MESSAGE]", len(str(args[0])) if args else 0, "chars")


def check_dependencies():
    """检查核心依赖库"""
    deps_status = {}

    # 核心依赖
    core_deps = ['numpy', 'matplotlib', 'scipy', 'PyQt5', 'PyQtAds']
    for dep in core_deps:
        try:
            __import__(dep)
            deps_status[dep] = True
        except ImportError:
            deps_status[dep] = False

    # 大模型相关依赖（可选）
    llm_deps = ['dashscope', 'python-dotenv']
    for dep in llm_deps:
        try:
            if dep == 'python-dotenv':
                __import__('dotenv')
            else:
                __import__(dep)
            deps_status[dep] = True
        except ImportError:
            deps_status[dep] = False

    return deps_status


def show_welcome():
    """显示欢迎信息"""
    safe_print("=" * 70)
    safe_print("    雷达仿真智能体系统 v3.0 - Radar Simulation Agent System")
    safe_print("=" * 70)
    safe_print("")
    safe_print("核心功能 / Core Features:")
    safe_print("  * 雷达信号仿真 / Radar Signal Simulation")
    safe_print("  * 目标检测跟踪 / Target Detection & Tracking")
    safe_print("  * 智能对话交互 / AI Chat Interaction")
    safe_print("  * 多线程处理 / Multi-threaded Processing")
    safe_print("  * PyQtAds 专业停靠窗口 / PyQtAds Professional Docking")
    safe_print("")


def launch_gui_mode():
    """启动PyQtAds GUI模式"""
    safe_print("正在启动 PyQtAds 专业版...")

    # 检查依赖
    deps = check_dependencies()

    missing_deps = [dep for dep in ['numpy', 'matplotlib', 'scipy', 'PyQt5', 'PyQtAds']
                   if not deps.get(dep, False)]

    if missing_deps:
        safe_print(f"错误：缺少依赖库: {', '.join(missing_deps)}")
        safe_print(f"安装命令: pip install {' '.join(missing_deps)}")
        return 1

    try:
        from gui.main_window_pyqtads import main as pyqtads_main
        safe_print("特性: Visual Studio 风格停靠、智能标签页、高性能渲染")
        return pyqtads_main()

    except Exception as e:
        safe_print(f"GUI启动失败: {str(e)}")
        safe_print("请尝试控制台模式: python main.py --console")
        return 1


def launch_console_mode():
    """启动控制台模式"""
    safe_print("正在启动控制台模式...")
    
    # 检查依赖
    deps = check_dependencies()
    core_missing = [dep for dep in ['numpy', 'matplotlib', 'scipy'] 
                   if not deps.get(dep, False)]
    if core_missing:
        safe_print(f"错误：缺少核心依赖: {', '.join(core_missing)}")
        safe_print(f"安装命令: pip install {' '.join(core_missing)}")
        return 1
    
    try:
        # 创建必要目录
        os.makedirs("logs", exist_ok=True)
        os.makedirs("data/export", exist_ok=True)
        
        from simulator.sim_controller import SimController
        from gui.chat_agent import GUIChatAgent

        # 初始化控制器
        sim_controller = SimController("logs/console.log")
        chat_agent = GUIChatAgent(sim_controller)
        
        safe_print("=" * 60)
        safe_print("控制台模式功能:")
        safe_print("* 目标管理 / Target Management")
        safe_print("* 雷达参数设置 / Radar Parameter Setting") 
        safe_print("* 仿真控制 / Simulation Control")
        safe_print("* 数据分析 / Data Analysis")
        safe_print("* 自然语言指令 / Natural Language Commands")
        safe_print("=" * 60)
        safe_print("")
        safe_print("示例命令:")
        safe_print("  '添加飞机目标在坐标(25,30,5)'")
        safe_print("  '设置雷达功率为1500瓦'")
        safe_print("  '开始仿真'")
        safe_print("  '步进5步'")
        safe_print("  '查看状态'")
        safe_print("  'exit' 或 '退出' 结束程序")
        safe_print("=" * 60)
        
        while True:
            try:
                user_input = input("\n雷达指令: ").strip()
                
                if user_input.lower() in ['exit', '退出', 'quit', 'q']:
                    safe_print("再见！")
                    break
                    
                if not user_input:
                    continue
                    
                # 使用聊天智能体处理指令
                response = chat_agent.process_message(user_input)
                safe_print(f"\n系统响应: {response}")
                
            except KeyboardInterrupt:
                safe_print("\n\n用户中断")
                break
            except Exception as e:
                safe_print(f"错误: {str(e)}")
                
        return 0
        
    except Exception as e:
        safe_print(f"控制台模式失败: {str(e)}")
        return 1


def show_status():
    """显示系统状态"""
    safe_print("系统状态:")
    safe_print("=" * 50)

    deps = check_dependencies()

    safe_print("核心依赖:")
    for dep in ['numpy', 'matplotlib', 'scipy', 'PyQt5', 'PyQtAds']:
        status = "OK" if deps.get(dep, False) else "缺失"
        safe_print(f"  {dep}: {status}")

    safe_print("\n大模型支持:")
    for dep in ['dashscope', 'python-dotenv']:
        status = "OK" if deps.get(dep, False) else "缺失"
        safe_print(f"  {dep}: {status}")

    # 检查API密钥
    api_key = os.getenv('DASHSCOPE_API_KEY')
    api_status = "已配置" if api_key else "未配置"
    safe_print(f"  API密钥: {api_status}")

    # 检查项目文件
    safe_print("\n项目结构:")
    key_dirs = ['gui', 'simulator', 'agents', 'llm']
    for dir_name in key_dirs:
        status = "OK" if os.path.isdir(dir_name) else "缺失"
        safe_print(f"  {dir_name}/: {status}")

    safe_print("\n可用模式:")
    if all(deps.get(dep, False) for dep in ['PyQt5', 'PyQtAds']):
        safe_print("  PyQtAds GUI模式")
    safe_print("  控制台模式")


def main():
    """主程序入口"""
    import argparse

    parser = argparse.ArgumentParser(
        description="雷达仿真智能体系统",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
启动模式示例:
  python main.py                    # GUI模式 (PyQtAds)
  python main.py --console          # 控制台模式
  python main.py --status           # 显示系统状态
        """
    )

    parser.add_argument(
        '--console', action='store_true',
        help='启动控制台模式'
    )

    parser.add_argument(
        '--status', action='store_true',
        help='显示系统状态'
    )

    args = parser.parse_args()

    # 显示欢迎信息
    show_welcome()

    # 根据参数选择模式
    if args.console:
        return launch_console_mode()
    elif args.status:
        show_status()
        return 0
    else:
        # 默认启动GUI模式
        result = launch_gui_mode()
        if result != 0:
            safe_print("\n其他启动选项:")
            safe_print("  python main.py --console          # 控制台模式")
            safe_print("  python main.py --status           # 显示状态")
        return result


if __name__ == "__main__":
    sys.exit(main())